﻿using System;
using System.Threading.Tasks;
using System.Net.Http;
using static WINPE_TOOLBOX.ReadOnlyConfig;
using System.Collections.Generic;
using System.Windows.Forms;
using System.IO;
using System.Linq;

namespace WINPE_TOOLBOX
{
    internal class Check
    {
        // 使用单例模式的 Config 实例
        private static readonly Config _config = Config.Instance;
        private static readonly ResourcePathConfig _resource = new ResourcePathConfig();

        // 异步方法：检测互联网连接
        public static async Task<bool> IsInternetConnectedAsync()
        {
            try
            {
                // 创建HttpClient实例，用于发送HTTP请求
                using (HttpClient client = new HttpClient())
                {
                    // 设置请求的超时时间为5秒，防止请求长时间挂起
                    client.Timeout = TimeSpan.FromSeconds(5);

                    // 尝试从指定的URL获取JSON数据
                    HttpResponseMessage response = await client.GetAsync("https://api.it0472.top/HotPE/GetUpdate/");
                    
                    // 检查响应是否成功（状态码200-299表示成功）
                    return response.IsSuccessStatusCode;
                }
            }
            catch (Exception)
            {
                // 如果发生任何异常，返回false，表示无法连接到互联网
                return false;
            }
        }

        public static async Task CheckPEResAsync()
        {
            try
            {
                // 确保 _config.Resources 和 _config.Resources.Pe 已初始化
                if (_config.Resources == null)
                {
                    _config.Resources = new ResourcesConfig();
                }
                if (_config.Resources.Pe == null)
                {
                    _config.Resources.Pe = new PeConfig();
                }

                // 更新本地已有资源列表
                _config.Resources.Pe.All = await Utils.TraverseFiles(_resource.Pe, "*.7z");
                _config.Resources.Pe.LocalWim = await Utils.TraverseFiles(_resource.InstallTemp, "*.wim");

                // 选择最新的资源
                if (_config.Resources.Pe.All.Count > 0 && !Directory.GetFiles(_resource.Pe, "*.aria2").Any())
                {
                    _config.Resources.Pe.New = _config.Resources.Pe.All[0];
                }
                else if (_config.Resources.Pe.LocalWim.Count > 0 && !Directory.GetFiles(_resource.InstallTemp, "*.aria2").Any())
                {
                    _config.Resources.Pe.New = _config.Resources.Pe.LocalWim[0];
                }
                else
                {
                    _config.Resources.Pe.New = string.Empty;
                }

                UpdateState();
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine($"Error in CheckPEResAsync: {ex.Message}");
            }
        }

        public static void UpdateState()
        {
            try
            {
                if (string.IsNullOrEmpty(_config.Resources.Pe.New))
                {
                    _config.State.Install = "noDown";
                }
                else if (_config.Environment.HotPEDrive.All.Count == 0)
                {
                    _config.State.Install = "noSetup";
                }
                else
                {
                    _config.State.Install = "ready";
                }
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine($"Error in UpdateState: {ex.Message}");
            }
        }

        public static void CheckBootMode()
        {

            //系统信息
            try
            {
                string temp = Utils.RunCmd(GlobalPaths.Tools + "BootMode.exe");
                if (temp.Contains("UEFI"))
                {
                    _config.Environment.Ware.System.Firmware = "UEFI";
                }
                else
                {
                    _config.Environment.Ware.System.Firmware = "Legacy";
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }


        }
    }
}
